package com.cmict.data.system.controller.admin.permission;

import com.cmict.data.framework.common.enums.CommonStatusEnum;
import com.cmict.data.framework.common.pojo.CommonResult;
import com.cmict.data.framework.common.pojo.PageResult;
import com.cmict.data.framework.excel.core.util.ExcelUtils;
import com.cmict.data.framework.operatelog.core.annotations.OperateLog;
import com.cmict.data.system.controller.admin.permission.vo.menu.MenuUpdateReqVO;
import com.cmict.data.system.convert.permission.RoleConvert;
import com.cmict.data.system.dal.dataobject.permission.MenuDO;
import com.cmict.data.system.dal.dataobject.permission.RoleDO;
import com.cmict.data.system.dal.mysql.permission.RoleMapper;
import com.cmict.data.system.service.permission.RoleService;
import com.cmict.data.system.controller.admin.permission.vo.role.*;
import com.cmict.data.system.controller.admin.permission.vo.role.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import static com.cmict.data.framework.common.pojo.CommonResult.success;
import static com.cmict.data.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;

@Api(tags = "管理后台 - 角色")
@RestController
@RequestMapping("/system/role")
@Validated
public class RoleController {

    @Resource
    private RoleService roleService;

    @Resource
    private RoleMapper roleMapper;

    @PostMapping("/create")
    @ApiOperation("创建角色")
    @PreAuthorize("@ss.hasPermission('system:role:create')")
    public CommonResult<Long> createRole(@Valid @RequestBody RoleCreateReqVO reqVO) {
        Boolean sucess = setMenuSort(reqVO);
        Long menuId = null;
        if(sucess){
            menuId = roleService.createRole(reqVO,null);
            return success(menuId);
        }
        RoleUpdateReqVO vo = new RoleUpdateReqVO();
        BeanUtils.copyProperties(reqVO,vo);
        vo.setId(menuId);
        roleService.updateRole(vo);
        return success(menuId);
    }

    @PutMapping("/update")
    @ApiOperation("修改角色")
    @PreAuthorize("@ss.hasPermission('system:role:update')")
    public CommonResult<Boolean> updateRole(@Valid @RequestBody RoleUpdateReqVO reqVO) {
        List<RoleDO> list = roleService.getRoleLisAll();
        int sort = 0;
        for (RoleDO roleDO:list) {
            if(!roleDO.getId().equals(reqVO.getId())) {
                if (sort != reqVO.getSort()) {
                    roleDO.setSort(sort);
                    // 更新到数据库
                    roleMapper.updateById(roleDO);
                    sort++;
                } else {
                    sort++;
                    roleDO.setSort(sort);
                    // 更新到数据库
                    roleMapper.updateById(roleDO);
                    sort++;
                }
            }
        }
        roleService.updateRole(reqVO);
        return success(true);
    }

    @PutMapping("/update-status")
    @ApiOperation("修改角色状态")
    @PreAuthorize("@ss.hasPermission('system:role:update')")
    public CommonResult<Boolean> updateRoleStatus(@Valid @RequestBody RoleUpdateStatusReqVO reqVO) {
        roleService.updateRoleStatus(reqVO.getId(), reqVO.getStatus());
        return success(true);
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除角色")
    @ApiImplicitParam(name = "id", value = "角色编号", required = true, example = "1024", dataTypeClass = Long.class)
    @PreAuthorize("@ss.hasPermission('system:role:delete')")
    public CommonResult<Boolean> deleteRole(@RequestParam("id") Long id) {
        roleService.deleteRole(id);
        return success(true);
    }

    @GetMapping("/get")
    @ApiOperation("获得角色信息")
    @PreAuthorize("@ss.hasPermission('system:role:query')")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = Long.class)
    public CommonResult<RoleRespVO> getRole(@RequestParam("id") Long id) {
        RoleDO role = roleService.getRole(id);
        return success(RoleConvert.INSTANCE.convert(role));
    }

    @GetMapping("/page")
    @ApiOperation("获得角色分页")
    @PreAuthorize("@ss.hasPermission('system:role:query')")
    public CommonResult<PageResult<RoleDO>> getRolePage(RolePageReqVO reqVO) {
        return success(roleService.getRolePage(reqVO));
    }

    @GetMapping("/list-all-simple")
    @ApiOperation(value = "获取角色精简信息列表", notes = "只包含被开启的角色，主要用于前端的下拉选项")
    public CommonResult<List<RoleSimpleRespVO>> getSimpleRoles() {
        // 获得角色列表，只要开启状态的
        List<RoleDO> list = roleService.getRoles(Collections.singleton(CommonStatusEnum.ENABLE.getStatus()));
        // 排序后，返回给前端
        list.sort(Comparator.comparing(RoleDO::getSort));
        return success(RoleConvert.INSTANCE.convertList02(list));
    }

    @GetMapping("/export")
    @OperateLog(type = EXPORT)
    @PreAuthorize("@ss.hasPermission('system:role:export')")
    public void export(HttpServletResponse response, @Validated RoleExportReqVO reqVO) throws IOException {
        List<RoleDO> list = roleService.getRoleList(reqVO);
        List<RoleExcelVO> data = RoleConvert.INSTANCE.convertList03(list);
        // 输出
        ExcelUtils.write(response, "角色数据.xls", "角色列表", RoleExcelVO.class, data);
    }

    public Boolean setMenuSort(RoleCreateReqVO roleVO) {
        List<RoleDO> list = roleService.getRoleLisAll();
        int sort = 0;
        for (RoleDO roleDO:list) {
            if(sort!=roleVO.getSort()){
                roleDO.setSort(sort);
                // 更新到数据库
                roleMapper.updateById(roleDO);
                sort++;
            }else{
                sort++;
                roleDO.setSort(sort);
                // 更新到数据库
                roleMapper.updateById(roleDO);
                sort++;
            }
        }
        return true;
    }
}
